<template>
    <div class="cart">
    <h2>Your Cart</h2>
    <p v-show="!cartProduct.length">
      <i>Please add some products to cart.</i>
    </p>  
    <ul>
      <li v-for="product in cartProduct" :key="product.id">
        {{ product.title }} - {{ product.price }} x {{ product.quantity }}
      </li>
    </ul>
    <p>总价--{{TotalPrice}}</p>
    <p>
      <button :disabled="!cartProduct.length" @click="checkout(cartProduct)">
        Checkout
      </button>
    </p>
   <p v-show="this.$store.state.CartAction.checkoutStatus">Checkout: {{this.$store.state.CartAction.checkoutStatus}}</p> 
  
  </div>
</template>

<script lang="ts">
import cartProduct from '@/model/cartProduct';
import cartApi from '../api/cartApi'
import ProductItem from '@/model/productItem';
    import { Component, Vue } from 'vue-property-decorator';
    import cartItem from '../model/cartItem'
    @Component
    export default class ShoppingCart  extends Vue {
         show:boolean = false;
         //这样写非响应式！！
         //cartItems:cartItem[] = this.$store.state.CartAction.items;
        get items():cartItem[]{
          return this.$store.state.CartAction.items;
        }
        //组装cartProduct
        get cartProduct():Array<cartProduct>{
               return this.items.map((cartItem:cartItem)=>{
                  const product  = this.$store.state.ProductionAction.products.find((pitem:ProductItem)=>pitem.id ===cartItem.id);
                  return new cartProduct(cartItem.id,product.title,product.price,cartItem.quantity);
                })
        }
        //计算总结
        get TotalPrice():number{
          let total :number= 0
            this.cartProduct.forEach((item:cartProduct) =>{
               total += item.price*item.quantity;
             })
             return total;
        }
           //结算
         async checkout(products:Array<cartProduct>){
            //拷贝新对象并缓存 state 的 items 数据
            const saveCartItems:cartItem[] =this.$store.state.CartAction.items;
            console.log("save "+saveCartItems);
            this.$store.state.CartAction.setCheckoutStatus(null)
            this.$store.state.CartAction.setCartItems([]);
            console.log(this.$store.state.CartAction.items,"[]???");
            const cartResult = await cartApi.buyProducts(products);
           // console.log(cartResult)
            //console.log(products)
            if(cartResult.success){
             this.$store.state.CartAction.setCheckoutStatus("successful")
                console.log("success")
            }else{
                this.$store.state.CartAction.setCheckoutStatus("failed")
                this.$store.state.CartAction.setCartItems(saveCartItems);
                //commit('setCartItems',{items:saveCartItems})
                console.log("failed")
            }
            
        }
       
    }
</script>

<style lang="scss" scoped>
  li{
    list-style: none;
  }
</style>